package com.unionftech.content_login.api.mock

import com.google.gson.Gson
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.SpUtils
import com.unionftech.content_login.api.mock.bean.MockAccountInfo
import okhttp3.RequestBody
import okio.Buffer
import retrofit2.mock.BehaviorDelegate
import java.nio.charset.Charset

class MockRegisterApi(private val delegate: BehaviorDelegate<RegisterMockApi>) : RegisterMockApi {
    private val gson: Gson by lazy { Gson() }
    override suspend fun register(body: RequestBody): ResponseResult<String> {
        val buffer = Buffer()
        body.writeTo(buffer)
        buffer.flush();
        val registerAccountJson = buffer.readString(Charset.defaultCharset())
        LogUtils.d("MockRegisterApi", "RequestBody--->$registerAccountJson")
        //将注册数据存入本地
        val result = saveRegister(registerAccountJson)
        return delegate.returningResponse(result)
            .register(body)
    }

    private fun saveRegister(registerAccountJson: String): ResponseResult<String?> {
        var lastResult = ResponseResult.buildSuccess("register success")
        val accountInfo = gson.fromJson(registerAccountJson, MockAccountInfo::class.java)
        val spKey = if (accountInfo.registerType == MockAccountInfo.TYPE_EMAIL) {
            MockServer.MOCK_EMAIL_ACCOUNT_LIST
        } else {
            MockServer.MOCK_PHONE_ACCOUNT_LIST
        }
        var set = SpUtils.getInstance().getStringSet(spKey)
        if (set == null) {
            set = mutableSetOf<String>()
            set.add(registerAccountJson)
        } else {
            var isExist = false
            for (strJson in set) {
                val info = gson.fromJson(strJson, MockAccountInfo::class.java)
                if (accountInfo.registerType == MockAccountInfo.TYPE_EMAIL) {
                    if (info.email == accountInfo.email) {
                        lastResult = ResponseResult.buildFail()
                        lastResult.msg = "user already exist"
                        isExist = true
                        break
                    }
                } else if (accountInfo.registerType == MockAccountInfo.TYPE_PHONE) {
                    if (info.phone == accountInfo.phone
                        && info.areaCode == accountInfo.areaCode
                    ) {
                        lastResult = ResponseResult.buildFail()
                        lastResult.msg = "user already exist"
                        isExist = true
                        break
                    }
                }
            }
            if (!isExist) {
                set.add(registerAccountJson)
            }
        }
        SpUtils.getInstance().put(spKey, set)
        LogUtils.d("register last set-------->$set")
        return lastResult
    }
}